package Threads;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class UseCallable {
    public static void main(String[] args) {
        // 1. 创建Callable接口实现类的实例
        SumUp SumUp = new SumUp();

        // 2. 使用FutureTask类包装Callable接口实现类的实例
        FutureTask<Integer> futureTask = new FutureTask<Integer>(SumUp);

        // 3. 创建Thread类对象，传递FutureTask类实例，任何多线程都需要Thread类
        Thread thread = new Thread(futureTask);

        // 4. 启动线程
        thread.start();

        // 5. 获取线程执行结果
        try {
            Object sum = futureTask.get();
            System.out.println("sum = " + sum);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

class SumUp implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " produce No. " + i + " product");
            if (i % 2 == 0)
                sum += i;
        }
        return sum;
    }

}
